#include "sdk.h"

IMPLEMENT_DYNAMIC_CLASS( M_Code_TreeCtrl, wxTreeCtrl )

BEGIN_EVENT_TABLE( M_Code_TreeCtrl, wxTreeCtrl )
  EVT_RIGHT_DOWN( M_Code_TreeCtrl::OnRightClick )
  EVT_KEY_DOWN( M_Code_TreeCtrl::OnKeyDown )
END_EVENT_TABLE()

M_Code_TreeCtrl::M_Code_TreeCtrl() : wxTreeCtrl() {
  Compare = &filesSort;
}

M_Code_TreeCtrl::M_Code_TreeCtrl( wxWindow* parent, int id ) :
  wxTreeCtrl( parent, id, wxDefaultPosition, wxDefaultSize, wxTR_EDIT_LABELS | wxTR_HAS_BUTTONS | wxTR_MULTIPLE | wxBORDER_NONE ) {
  Compare = &filesSort;
}

void M_Code_TreeCtrl::SetCompareFunction( const int ptvs ) {
  if( !( ptvs & ptvsUseFolders ) && ( ptvs & ptvsHideFolderName ) ) {
    Compare = &filesSortNameOnly;
  } else {
    Compare = &filesSort;
  }
}

wxTreeItemId M_Code_TreeCtrl::GetPrevVisible( const wxTreeItemId& item ) const {
  wxTreeItemId previous = GetPrevSibling( item );
  if( previous.IsOk() ) {
    while( ItemHasChildren( previous ) && IsExpanded( previous ) ) {
      wxTreeItemId child = GetLastChild( previous );
      if( !child.IsOk() ) {
        break;
      } else
      { previous = child; }
    }
  } else {
    previous = GetItemParent( item );
  }
  return previous;
}

void M_Code_TreeCtrl::OnRightClick( wxMouseEvent& event ) {
  int flags;
  HitTest( wxPoint( event.GetX(), event.GetY() ), flags );
  if( flags & ( wxTREE_HITTEST_ABOVE | wxTREE_HITTEST_BELOW | wxTREE_HITTEST_NOWHERE ) ) {
    wxCommandEvent e( wxEVT_COMMAND_RIGHT_CLICK, GetID() );
    wxPostEvent( GetParent(), e );
  } else {
    event.Skip();
  }
}

void M_Code_TreeCtrl::OnKeyDown( wxKeyEvent& event ) {
  if( event.GetModifiers() != wxMOD_NONE ) {
    event.Skip();
    return;
  }
  wxArrayTreeItemIds selections;
  if( GetSelections( selections ) < 1 ) {
    event.Skip();
    return;
  }
  long keycode = event.GetKeyCode();
  wxTreeItemId itemId  = selections[0];
  if( !itemId.IsOk() ) {
    event.Skip();
    return;
  }
  switch( keycode ) {
    case WXK_RETURN:
    case WXK_NUMPAD_ENTER: {
      wxTreeEvent te = wxTreeEvent( wxEVT_COMMAND_TREE_ITEM_ACTIVATED, this, itemId );
      wxPostEvent( this, te );
      break;
    }
    default:
      event.Skip();
  }
}

int M_Code_TreeCtrl::filesSort( const ProjectFile* arg1, const ProjectFile* arg2 ) {
  if( arg1 && arg2 ) {
    return wxStricmp( arg1->file.GetFullPath(), arg2->file.GetFullPath() );
  }
  return 0;
}

int M_Code_TreeCtrl::filesSortNameOnly( const ProjectFile* arg1, const ProjectFile* arg2 ) {
  if( arg1 && arg2 ) {
    return wxStricmp( arg1->file.GetFullName(), arg2->file.GetFullName() );
  }
  return 0;
}

int M_Code_TreeCtrl::OnCompareItems( const wxTreeItemId& item1, const wxTreeItemId& item2 ) {
  return Compare( ( ( FileTreeData* )GetItemData( item1 ) )->GetProjectFile(), ( ( FileTreeData* )GetItemData( item2 ) )->GetProjectFile() );
}
